package dao;

import model.Group;
import org.hibernate.Session;
import util.HibernateUtil;

import java.util.ArrayList;
import java.util.List;


public class GroupDaoImpl implements GroupDao {
    Session session;
    public void createGroup(Group group) {
        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.save(group);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }

    public Group readGroup(int index) {
        Group group = null;
        try{
            session = HibernateUtil.getSession().openSession();
            group = (Group) session.load(Group.class,index);

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
        return group;
    }

    public void updateGroup(Group group) {
        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.update(group);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }

    public void deleteGroup(Group group) {

        try{
            session = HibernateUtil.getSession().openSession();
            session.beginTransaction();
            session.delete(group);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (session.isOpen()|| session != null){
                session = null;
            }
        }
    }

    public List<Group> getAllGroups() {
        Session session = null;
        List<Group> groups = new ArrayList<Group>();
        try {
            session = HibernateUtil.getSession().openSession();
            groups = session.createCriteria(Group.class).list();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
        return groups;
    }
}
